package com.lupan.mutithred.cp9_ForkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

/**
 * 说明：
 *
 * @author lupan
 * @version 2017/5/25 10:15
 */
public class MyRecursiveTask extends RecursiveTask<Integer> {

    private int beginPosition;
    private int endPosition;

    public MyRecursiveTask(int beginPosition, int endPosition) {
        this.beginPosition = beginPosition;
        this.endPosition = endPosition;
    }

    @Override
    protected Integer compute() {
        System.out.println(Thread.currentThread().getName()+"........");
        System.out.println(String.format("begin=%s end=%s",beginPosition,endPosition));
        if(beginPosition != endPosition){
            System.out.println("beginPosition != endPosition");
            int middlePosition = (beginPosition+endPosition)/2;
            MyRecursiveTask left = new MyRecursiveTask(beginPosition,middlePosition);
            MyRecursiveTask right = new MyRecursiveTask(middlePosition+1,endPosition);
            invokeAll(left, right);
            try {
                return left.get()+right.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        return endPosition;
    }
}
